<?php

/**
 * 系统管理
 * @author Administrator
 */

namespace Operation\Controller;

use Think\Controller;
use Think\IReq;
use Think\IFilter;
use Think\IFile;
use Think\ITime;
use Think\Page;
use Think\JSON;

class SystemController extends ComController {

    /**
     * @brief 地区列表
     */
    public function area_list() {
        $area = M('areas')->where(array('parent_id' => 0))->select();
        $this->assign('area', JSON::encode($area));
        $this->display();
    }

    /**
     * @brief 地域更新
     */
    public function area_update() {
        $area_id = IFilter::act(IReq::get('area_id'));
        $area_name = IFilter::act(IReq::get('area_name'));
        $area_sort = IFilter::act(IReq::get('area_sort'));
        $parent_id = IFilter::act(IReq::get('parent_id'));

        $areasDB = M('areas');

        //添加
        if ($parent_id !== '') {
            $addData = array('parent_id' => $parent_id, 'area_name' => $area_name, 'sort' => 99);
            $area_id = $areasDB->add($addData);
            $addData['area_id'] = $area_id;
            die(JSON::encode(array('isSuccess' => true, 'data' => $addData)));
        }
        //修改
        else {
            $updateData = array();
            if ($area_name) {
                $updateData['area_name'] = $area_name;
            }

            if ($area_sort) {
                $updateData['sort'] = $area_sort;
            }
            $updateData['area_id'] = $area_id;
            $areasDB->save($updateData);
        }
    }

    /**
     * @brief 地域删除
     */
    public function area_del() {
        $area_id = IFilter::act(IReq::get('id'), 'int');
        $areasDB = M('areas');
        $areasDB->where(array('area_id' => $area_id))->delete();
    }
    
     /**
     * @brief 管理员列表
     */
    public function admin_list() {
        $p = IFilter::act(IReq::get('p'), 'int') ? IFilter::act(IReq::get('p'), 'int') : 1;
        $page = '20';
        $where = array(
            'a.is_del' => 0
        );
        $join = 'left join sm_admin_role as b on a.role_id = b.id';
        $field = 'a.*,b.name as role_name';
        $adminObj = M('admin as a');
        $admin = $adminObj->where($where)->join($join)->order($order)->field($field)->page($p . ",$page")->select();
        //dump($admin);die;
        $this->assign('admin',$admin);
        $this->display();
    }
    
    /**
     *  @brief 添加管理员
     */
    public function admin_edit(){
        $admin_id = IFilter::act(IReq::get('id'), 'int');
        if($admin_id){
            $adminObj = M('admin');
            $adminRow = $adminObj->find($admin_id);
        }
        $adminRow = $adminRow ? $adminRow : $this->adminRow;
        $this->assign('adminRow',$adminRow);
        
        $roleObj = M('admin_role');
        $admin_role = $roleObj->where($where)->select();
        $this->assign('admin_role',$admin_role);
        $this->display();
    }

    /*
     * 添加/编辑管理员
     */
    public function admin_edit_act(){
        $adminRow = array(
            'admin_name' => IFilter::act(IReq::get('admin_name')),
            'role_id' => IFilter::act(IReq::get('role_id')),
            'email' => IFilter::act(IReq::get('email')),
        );
        if(IFilter::act(IReq::get('password')) && IFilter::act(IReq::get('password')) == IFilter::act(IReq::get('repassword'))){
            $adminRow['password'] = md5(IFilter::act(IReq::get('password')));
        }
        $adminObj = M('admin');
        if(IFilter::act(IReq::get('id'))){
            $adminRow['id'] = IFilter::act(IReq::get('id'));
            $res = $adminObj->save($adminRow);
        }else{
            $adminRow['create_time'] = ITime::getDateTime();
            $res = $adminObj->add($adminRow);
        }
        if($res){
            $this->redirect('admin_list');
        }else{
            $this->adminRow = $adminRow;
            $this->redirect('admin_edit');
        }
    }

    /**
     * @brief 角色列表
     */
    public function role_list() {
        $p = IFilter::act(IReq::get('p'), 'int') ? IFilter::act(IReq::get('p'), 'int') : 1;
        $page = '20';
        $where = array(
            'is_del' => 0
        );
        $roleObj = M('admin_role');
        $role = $roleObj->where($where)->page($p . ",$page")->select();
        $this->assign('role', $role);
        $this->display();
    }
    
    /**
     * 添加/编辑角色 
     */
    public function role_edit() {
        $id = IFilter::act(IReq::get('id'), 'int');
        if ($id) {
            $roleObj = M('admin_role');
            $roleRow = $roleObj->find($id);
        }
        //获取权限码分组形势
        $rightObj = M('right');
        $where = array(
            'is_del' => 0
        );
        $rightData = $rightObj->where($where)->order('name asc')->select();

        $rightArray = array();
        $rightUndefined = array();
        foreach ($rightData as $key => $item) {
            if($roleRow['rights']){
                if(stripos($roleRow['rights'],",".$item['right'].",") !== false){
                    $item['is_focus'] = true;
                }  else {
                    $item['is_focus'] = false;
                }
            }
            preg_match('/\[.*?\]/', $item['name'], $localPre);
            if (isset($localPre[0])) {
                $arrayKey = trim($localPre[0], '[]');
                //dump($item);die;
                $rightArray[$arrayKey][] = $item;
            } else {
                $rightUndefined[] = $item;
            }
        }

        //dump($rightUndefined);die;
        $roleRow = $roleRow ? $roleRow : $this->roleRow;
        $this->assign('roleRow', $roleRow);
        $this->assign('rightArray', $rightArray);
        $this->assign('rightUndefined', $rightUndefined);
        $this->display();
    }

    public function role_edit_act() {
        $id = IFilter::act(IReq::get('id', 'post'));
        $roleObj = M('admin_role');

        //要入库的数据
        $dataArray = array(
            'id' => $id,
            'name' => IFilter::string(IReq::get('name', 'post')),
            'rights' => null,
        );

        //检查权限码是否为空
        $rights = IFilter::act(IReq::get('right', 'post'));
        if (empty($rights) || $rights[0] == '') {
            $this->roleRow = $dataArray;
            $this->redirect('role_edit', false);
            Util::showMessage('请选择要分配的权限');
        }

        //拼接权限码
        $rightsArray = array();
        $rightObj = M('right');
        $where = array(
            'id in (' . join(",", $rights) . ')'
        );
        $rightList = $rightObj->where($where)->select();
        foreach ($rightList as $key => $val) {
            $rightsArray[] = trim($val['right'], ',');
        }

        $dataArray['rights'] = empty($rightsArray) ? '' : ',' . join(',', $rightsArray) . ',';
        if ($id) {
            $dataArray['id'] = $id;
            $roleObj->save($dataArray);
        } else {
            $roleObj->add($dataArray);
        }
        $this->redirect('role_list');
    }
    
    /**
     *  权限资源 
     */
    public function right_list(){
        $rightObj = M('right');
        $where = array(
            'is_del' => 0
        );
        $right = $rightObj->where($where)->select();
        $this->assign('right', $right);
        $this->display();
    }
    
    /**
     * 添加/编辑权限 
     */
    public function right_edit(){
        $id = IFilter::act(IReq::get('id'));
        if ($id) {
            $rightObj = M('right');
            $rightRow = $rightObj->find($id);
        }
        if($rightRow['right']){
            $rightArray = explode(',',trim($rightRow['right'],','));
            $this->assign('rightArray', $rightArray);
        }
        $rightRow = $rightRow ? $rightRow : $this->rightRow;
        $this->assign('rightRow', $rightRow);
        $this->display();
    }
    
    //[权限管理][权限] 权限修改，添加[动作]
    public function right_edit_act() {
        $id = IFilter::act(IReq::get('id', 'post'));
        $right = IFilter::act(array_unique(IReq::get('right')));
        $name = IFilter::act(IReq::get('name', 'post'));

        if (!$right) {
            $this->rightRow = array(
                'id' => $id,
                'name' => $name,
            );
            $this->redirect('right_edit', false);
            Util::showMessage('权限码不能为空');
            exit;
        }

        $dataArray = array(
            'id' => $id,
            'name' => $name,
            'right' => join(',', $right),
        );

        $rightObj = M('right');
        if ($id) {
            $dataArray['id'] = $id;
            $rightObj->save($dataArray);
        } else {
            $rightObj->add($dataArray);
        }
        $this->redirect('right_list');
    }

    //[权限管理][权限] 权限更新操作 [回收站操作][物理删除]
    public function right_update() {
        $id = IFilter::act(IReq::get('id'), 'int');

        //是否为回收站操作
        $isRecycle = IReq::get('recycle');

        if (!empty($id)) {
            $obj = M('right');
            $where = Util::joinStr($id);

            if ($isRecycle === null) {
                $obj->del($where);
                $this->redirect('right_recycle');
            } else {
                //回收站操作类型
                $is_del = ($isRecycle == 'del') ? 1 : 0;
                $obj->setData(array('is_del' => $is_del));
                $obj->update($where);
                $this->redirect('right_list');
            }
        } else {
            if ($isRecycle == 'del')
                $this->redirect('right_list', false);
            else
                $this->redirect('right_recycle', false);

            Util::showMessage('请选择要操作的权限ID');
        }
    }

    //清理缓存
    public function clearCache() {
        $runtimePath = APP_PATH . 'Runtime';
        $result = IFile::clearDir($runtimePath);

        if ($result == true)
            echo 1;
        else
            echo -1;
    }

    //列出控制器
    public function list_controller($module = 'Operation') {

        if (empty($module))
            return null;
        $module_path = APP_PATH . $module . '/Controller';  //控制器路径

        if (!is_dir($module_path))
            return null;
        $module_path .= '/*.class.php';
        $ary_files = glob($module_path);
        $files = array();
        foreach ($ary_files as $file) {
            if (is_dir($file)) {
                continue;
            } else {
                $files[] = basename($file, C('DEFAULT_C_LAYER') . '.class.php');
            }
        }
        echo JSON::encode($files);
    }

    //列出某个控制器的action动作和视图
    public function list_action() {
        $ctrlId = IReq::get('ctrlId');
        if ($ctrlId != '') {
            $con = A($ctrlId);
            $functions = get_class_methods($con); //排除部分方法 
            $inherents_functions = array(
                '_initialize', '__construct', 'getActionName', 'isAjax', 'display', 'show', 'fetch', 'buildHtml', 'assign', '__set', 'get', '__get', '__isset', '__call', 'error', 'success', 'ajaxReturn', 'redirect', '__destruct', '_empty');
            $customer_functions = array();
            foreach ($functions as $func) {
                if (!in_array($func, $inherents_functions)) {
                    $customer_functions[] = $func;
                }
            }
            echo JSON::encode($customer_functions);
        }
    }

}